package com.hanshg.cherry.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanshg.cherry.base.core.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 柠檬水
 */
@Component
@Slf4j
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Value("${spring.security.loginType}")
    private String loginType;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败");

        if (loginType.equalsIgnoreCase(Constants.LOGIN_TYPE_JSON)) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            Map<String, Object> map = new HashMap<>();
            if (exception instanceof BadCredentialsException || exception instanceof UsernameNotFoundException) {
                map.put("message", exception.getMessage());
            } else if (exception instanceof LockedException) {
                map.put("message", "账户被锁定，请联系柠檬水小哥哥!");
            } else if (exception instanceof DisabledException) {
                map.put("message", "账户被禁用，请联系柠檬水小哥哥!");
            } else if (exception instanceof AccountExpiredException) {
                map.put("message", "账户已过期，请联系柠檬水小哥哥!");
            } else if (exception instanceof CredentialsExpiredException) {
                map.put("message", "密码已过期，请联系柠檬水小哥哥!");
            } else {
                map.put("message", "登录失败,请联系柠檬水小哥哥!");
            }
            response.getWriter().write(objectMapper.writeValueAsString(map));
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
